<!DOCTYPE html>
<html>
<head>
    <title>记账系统 - 收支管理</title>
    <link rel="stylesheet" href="../static/css/ej.css">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap CSS -->
    <link href="../static/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <!-- Bootstrap Icons -->
    <link href="../static/bootstrap/icons/bootstrap-icons.css" rel="stylesheet">
    <style>
        .account-form {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .form-group textarea {
            height: 80px;
            resize: vertical;
        }
        .form-row {
            display: flex;
            gap: 15px;
            margin-bottom: 15px;
        }
        .form-row .form-group {
            flex: 1;
            margin-bottom: 0;
        }
        .required::after {
            content: " *";
            color: #d32f2f;
        }
        .submit-btn {
            background-color: #c0a36c;
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 20px;
        }
        .submit-btn:hover {
            background-color: #a88c5a;
        }
        .loading {
            text-align: center;
            padding: 20px;
            color: #666;
        }
        .error {
            color: #d32f2f;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        .success {
            color: #2e7d32;
            padding: 10px;
            background-color: #e8f5e8;
            border-radius: 4px;
            margin: 10px 0;
        }
        .price-input {
            text-align: right;
        }
        .readonly-input {
            background-color: #f5f5f5;
            cursor: not-allowed;
        }
        .tab-content {
            margin-top: 20px;
        }
        .nav-tabs .nav-link.active {
            background-color: #fff;
            border-bottom-color: #fff;
            color: #c0a36c;
            font-weight: bold;
        }
        .nav-tabs .nav-link {
            color: #666;
        }
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .summary-value {
            font-size: 24px;
            font-weight: bold;
        }
        .filter-section {
            background-color: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .record-table {
            width: 100%;
            border-collapse: collapse;
        }
        .record-table th,
        .record-table td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .record-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .record-table tr:hover {
            background-color: #f5f5f5;
        }
        .income-row {
            background-color: #e8f5e8;
        }
        .expense-row {
            background-color: #ffebee;
        }
        .settled-true {
            color: #2e7d32;
        }
        .settled-false {
            color: #d32f2f;
        }
        .accounted-true {
            color: #1976d2;
        }
        .accounted-false {
            color: #757575;
        }
        .accounted-partial {
            color: #ff9800;
        }

        /* 响应式优化 */
        @media (max-width: 768px) {
            /* 移动端表单布局优化 */
            .form-row {
                flex-direction: column;
                gap: 10px;
            }
            
            .form-row .form-group {
                margin-bottom: 10px;
            }
            
            /* 移动端表格优化 */
            .record-table {
                display: block;
                overflow-x: auto;
                white-space: nowrap;
            }
            
            .record-table th,
            .record-table td {
                padding: 6px;
                font-size: 14px;
            }
            
            /* 移动端按钮优化 */
            .submit-btn {
                width: 100%;
                padding: 15px;
                font-size: 18px;
            }
            
            /* 移动端卡片布局优化 */
            .summary-card {
                margin-bottom: 15px;
            }
            
            /* 移动端标签页优化 */
            .nav-tabs .nav-link {
                padding: 8px 12px;
                font-size: 14px;
            }
            
            /* 移动端筛选区域优化 */
            .filter-section {
                padding: 10px;
            }
            
            /* 移动端表单元素优化 */
            .form-group input, 
            .form-group select, 
            .form-group textarea {
                padding: 12px;
                font-size: 16px; /* 防止iOS缩放 */
            }
            
            /* 移动端金额显示优化 */
            .price-input {
                font-size: 18px;
            }
        }

        @media (max-width: 576px) {
            /* 超小屏幕优化 */
            .account-form {
                margin: 10px;
                padding: 15px;
            }
            
            h2 {
                font-size: 20px;
                padding: 0 10px;
            }
            
            /* 移动端表格进一步优化 */
            .record-table {
                font-size: 12px;
            }
            
            .record-table th,
            .record-table td {
                padding: 4px;
            }
            
            /* 移动端按钮组优化 */
            .btn-group .btn {
                padding: 6px 8px;
                font-size: 12px;
            }
        }

        /* 平板设备优化 */
        @media (min-width: 769px) and (max-width: 1024px) {
            .form-row {
                gap: 10px;
            }
            
            .account-form {
                padding: 15px;
            }
        }

        /* 防止移动端输入框缩放 */
        @media screen and (max-width: 768px) {
            input[type="text"],
            input[type="number"],
            input[type="date"],
            select,
            textarea {
                font-size: 16px !important;
            }
        }

        /* 移动端友好的滚动条 */
        .record-table::-webkit-scrollbar {
            height: 6px;
        }
        
        .record-table::-webkit-scrollbar-thumb {
            background: #ccc;
            border-radius: 3px;
        }

        /* 移动端卡片布局样式 */
        .record-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            margin-bottom: 15px;
            padding: 15px;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .income-card {
            border-left: 4px solid #2e7d32;
            background-color: #e8f5e8;
        }
        
        .expense-card {
            border-left: 4px solid #d32f2f;
            background-color: #ffebee;
        }
        
        .record-card-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        
        .record-type {
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
        }
        
        .income-card .record-type {
            background-color: #2e7d32;
            color: white;
        }
        
        .expense-card .record-type {
            background-color: #d32f2f;
            color: white;
        }
        
        .record-card-body div {
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .record-card-actions {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            padding-top: 10px;
            border-top: 1px solid #eee;
        }
        
        .record-card-actions .btn {
            flex: 1;
            padding: 6px 12px;
            font-size: 14px;
        }

        /* 移动端表格隐藏，显示卡片 */
        @media (max-width: 768px) {
            .record-table thead {
                display: none;
            }
            
            .record-table tbody tr {
                display: none;
            }
            
            #recordsTableBody {
                display: block;
            }
            
            .record-card {
                display: block;
            }
        }

        /* PC端卡片隐藏，显示表格 */
        @media (min-width: 769px) {
            .record-card {
                display: none;
            }
            
            .record-table thead {
                display: table-header-group;
            }
            
            .record-table tbody tr {
                display: table-row;
            }
        }

        /* 统计汇总表格响应式优化 */
        .summary-table-container {
            overflow-x: auto;
            margin-bottom: 20px;
        }
        
        .summary-table {
            min-width: 500px;
            width: 100%;
        }
        
        /* 移动端统计卡片样式 */
        .summary-card-item {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            background-color: #fff;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        .summary-card-header {
            font-weight: bold;
            margin-bottom: 10px;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
            color: #c0a36c;
        }
        
        .summary-card-detail {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .summary-income {
            color: #2e7d32;
        }
        
        .summary-expense {
            color: #d32f2f;
        }
        
        .summary-net {
            font-weight: bold;
            border-top: 1px solid #eee;
            padding-top: 8px;
            margin-top: 8px;
        }

        /* 移动端分类标题样式 */
        .category-header-mobile {
            margin: 20px 0 10px 0;
            padding: 10px 0;
            border-bottom: 2px solid #c0a36c;
            color: #c0a36c;
            font-weight: bold;
        }

        .category-header-mobile h5 {
            margin: 0;
            font-size: 18px;
        }

        /* 移动端收入卡片样式 */
        .income-card-mobile {
            border-left: 4px solid #2e7d32;
            background-color: #e8f5e8;
        }

        /* 移动端支出卡片样式 */
        .expense-card-mobile {
            border-left: 4px solid #d32f2f;
            background-color: #ffebee;
        }

        /* 移动端统计表格隐藏，显示卡片 */
        @media (max-width: 768px) {
            .summary-table {
                display: none;
            }
            
            .summary-card-view {
                display: block;
            }
        }

        /* PC端统计卡片隐藏，显示表格 */
        @media (min-width: 769px) {
            .summary-card-view {
                display: none;
            }
            
            .summary-table {
                display: table;
            }
        }
    </style>
</head>
<body style="background-color:#fffbf6">
    
    <!-- 返回主菜单按钮
    <div style="max-width: 1200px; margin: 20px auto 10px auto; padding: 0 20px;">
        <a href="/ej_index" class="btn btn-outline-secondary btn-sm" style="margin-bottom: 10px;">
            <i class="bi bi-arrow-left"></i> 返回主菜单
        </a>
    </div> -->
    
    <h2 style="max-width: 1200px; margin: 20px auto 20px auto; padding: 0 20px;">记账系统 - 收支管理</h2>

    <!-- 导航标签 -->
    <ul class="nav nav-tabs" id="accountTabs" style="max-width: 1200px; margin: 0 auto;">
        <li class="nav-item">
            <a class="nav-link active" id="record-tab" data-bs-toggle="tab" href="#record">记账</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="records-tab" data-bs-toggle="tab" href="#records">记录查询</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="summary-tab" data-bs-toggle="tab" href="#summary">已入账账户统计</a>
        </li>
        <li class="nav-item">
            <a class="nav-link" id="account-summary-tab" data-bs-toggle="tab" href="#account-summary">分类统计</a>
        </li>
    </ul>

    <div class="tab-content" style="max-width: 1200px; margin: 0 auto;">
        <!-- 记账标签页 -->
        <div class="tab-pane fade show active" id="record">
            <div id="loading" class="loading" style="display: none;">正在加载...</div>
            <div id="error" class="error" style="display: none;"></div>
            <div id="success" class="success" style="display: none;"></div>

            <form id="accountForm" class="account-form">
                <!-- 基本信息 -->
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">结算日期</label>
                        <input type="date" id="settlement_date" name="settlement_date" required>
                    </div>
                    <div class="form-group">
                        <label class="required">收支类型</label>
                        <select id="settlement_type" name="settlement_type" required onchange="updateCategories()">
                            <option value="">请选择类型</option>
                            <option value="income">收入</option>
                            <option value="expense">支出</option>
                        </select>
                    </div>
                </div>

                <!-- 项目信息 -->
                <div class="form-row">
                    <div class="form-group">
                        <label>项目类型</label>
                        <select id="project_name" name="project_name">
                            <option value="ejj" selected>ejj</option>
                            <option value="dd">dd</option>
                            <option value="fruit">fruit</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="required">结算内容</label>
                        <input type="text" id="item_name" name="item_name" required placeholder="请输入结算内容">
                    </div>
                </div>

                <!-- 分类信息 -->
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">一级分类</label>
                        <select id="category_id" name="category_id" required onchange="updateSubcategories()">
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="required">二级分类</label>
                        <select id="subcategory_id" name="subcategory_id" required>
                            <option value="">请选择子分类</option>
                        </select>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>结算对象</label>
                        <input type="text" id="settled_with" name="settled_with" placeholder="请输入结算对象（可选）">
                    </div>
                </div>

                <!-- 账户信息 -->
                <div class="form-row">
                    
                    <div class="form-group">
                        <label>支付方式</label>
                        <select id="payment_method" name="payment_method">
                            <option value="">请选择支付方式</option>
                            <option value="cash">现金</option>
                            <option value="bank">银行转账</option>
                            <option value="alipay">支付宝</option>
                            <option value="wechat">微信支付</option>
                            <option value="other">其他</option>
                        </select>
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label>结算单号</label>
                        <input type="text" id="settlement_id" name="settlement_id" placeholder="自动生成（可选）">
                    </div>
                </div>

                <!-- 金额信息 -->
                <div class="form-row">
                    <div class="form-group">
                        <label class="required">数量</label>
                        <input type="number" step="0.01" id="quantity" name="quantity" value="1.00" class="price-input" min="0.01" required onchange="calculateAmount()">
                    </div>
                    <div class="form-group">
                        <label class="required">单价 (元)</label>
                        <input type="number" step="0.01" id="unit_price" name="unit_price" value="0.00" class="price-input" min="0" required onchange="calculateAmount()">
                    </div>
                </div>

                <div class="form-row">
                    <div class="form-group">
                        <label class="required">金额 （元）</label>
                        <input type="number" step="0.01" id="amount" name="amount" value="0.00" class="price-input readonly-input" readonly>
                    </div>
                    <div class="form-group">
                        <label class="required">结算垫支/收款人</label>
                        <input type="text" id="settler_name" name="settler_name" required placeholder="请输入收款人姓名">
                    </div>
                </div>

                <!-- 结算状态 -->
                <div class="form-row">
                    <div class="form-group">
                        <label>工作帐户结算金额</label>
                        <input type="number" step="0.01" id="settlement_amount" name="settlement_amount" value="0.00" class="price-input" min="0" placeholder="请输入结算金额" onchange="calculateAccountedStatus()">
                    </div>
                    <div class="form-group">
                        <label>入账状态</label>
                        <input type="text" id="accounted_status_display" class="readonly-input" readonly>
                        <input type="hidden" id="accounted_status" name="accounted_status" value="pending">
                    </div>
                    <div class="form-group">
                        <label>工作帐户</label>
                        <select id="account_name" name="account_name">
                            <option value="">请选择工作帐户</option>
                        </select>
                    </div>
                </div>

                <!-- 备注 -->
                <div class="form-group">
                    <label>备注</label>
                    <textarea id="comment" name="comment" placeholder="请输入备注信息"></textarea>
                </div>

                <button type="submit" class="submit-btn">保存记账信息</button>
            </form>
        </div>

        <!-- 记录查询标签页 -->
        <div class="tab-pane fade" id="records">
            <div class="filter-section">
                <h4>筛选条件</h4>
                <div class="form-row">
                    <div class="form-group">
                        <label>开始日期</label>
                        <input type="date" id="start_date" name="start_date" onchange="loadRecords()">
                    </div>
                    <div class="form-group">
                        <label>结束日期</label>
                        <input type="date" id="end_date" name="end_date" onchange="loadRecords()">
                    </div>
                    <div class="form-group">
                        <label>收支类型</label>
                        <select id="filter_type" name="filter_type" onchange="loadRecords()">
                            <option value="">全部</option>
                            <option value="income">收入</option>
                            <option value="expense">支出</option>
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>入账状态</label>
                        <select id="filter_accounted_status" name="filter_accounted_status" onchange="loadRecords()">
                            <option value="">全部</option>
                            <option value="pending">待入账</option>
                            <option value="completed">已入账</option>
                            <option value="partial">部分入账</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label>项目类型</label>
                        <select id="filter_project_name" name="filter_project_name" onchange="loadRecords()">
                            <option value="">全部项目</option>
                            <!-- 动态加载的项目选项 -->
                        </select>
                    </div>
                </div>
                <div class="form-row">
                    <div class="form-group">
                        <label>快速查询</label>
                        <div style="display: flex; gap: 10px;">
                            <button type="button" class="btn btn-outline-secondary" onclick="queryThisMonth()">查询本月</button>
                            <button type="button" class="btn btn-outline-secondary" onclick="queryThisYear()">查询本年</button>
                        </div>
                    </div>
                </div>
            </div>

            <div id="recordsLoading" class="loading" style="display: none;">正在加载记录...</div>
            <div id="recordsError" class="error" style="display: none;"></div>

            <div id="recordsContainer">
                <table class="record-table">
                        <thead>
                        <tr>
                            <th style="width: 100px;">日期</th>
                            <th style="width: 60px;">类型</th>
                            <th style="width: 100px;">结算对象</th>
                            <th style="width: 150px;">结算内容</th>
                            <th style="width: 80px;">项目类型</th>
                            <th style="width: 120px;">分类</th>
                            <th style="width: 100px;">金额（元）</th>
                            <th style="width: 100px;">未结算金额（元）</th>
                            <th style="width: 80px;">入账状态</th>
                            <th style="width: 120px;">操作</th>
                        </tr>
                    </thead>
                    <tbody id="recordsTableBody">
                        <tr>
                            <td colspan="10" style="text-align: center;">请选择筛选条件加载数据</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- 入账账户统计标签页 -->
        <div class="tab-pane fade" id="summary">
            <div class="filter-section">
                <h4>统计条件</h4>
                <div class="form-row">
                    <div class="form-group">
                        <label>开始日期</label>
                        <input type="date" id="summary_start_date" name="summary_start_date" onchange="loadAccountSummaryForSummaryTab()">
                    </div>
                    <div class="form-group">
                        <label>结束日期</label>
                        <input type="date" id="summary_end_date" name="summary_end_date" onchange="loadAccountSummaryForSummaryTab()">
                    </div>
                    <div class="form-group">
                        <label>账户名称</label>
                        <select id="summary_account" name="summary_account" onchange="loadAccountSummaryForSummaryTab()">
                            <option value="">全部账户</option>
                        </select>
                    </div>
                </div>
            </div>

            <div id="summaryLoading" class="loading" style="display: none;">正在生成统计...</div>
            <div id="summaryError" class="error" style="display: none;"></div>

            <div id="summaryContainer">
                <div class="form-row">
                    <div class="form-group">
                        <div class="summary-card">
                            <h5>总收入</h5>
                            <div class="summary-value" id="totalIncome">0.00 元</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                            <h5>总支出</h5>
                            <div class="summary-value" id="totalExpense">0.00 元</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                            <h5>净收益</h5>
                            <div class="summary-value" id="netIncome">0.00 元</div>
                        </div>
                    </div>
                </div>

                <!-- 移动端卡片视图 -->
                <div id="summaryCardView" class="summary-card-view">
                    <div style="text-align: center; padding: 20px; color: #666;">
                        请选择日期和账户查看统计
                    </div>
                </div>
            </div>
        </div>

        <!-- 分类统计标签页 -->
        <div class="tab-pane fade" id="account-summary">
            <div class="filter-section">
                <h4>分类统计条件</h4>
                <div class="form-row">
                    <div class="form-group">
                        <label>开始日期</label>
                        <input type="date" id="category_start_date" name="category_start_date" onchange="loadCategorySummary()">
                    </div>
                    <div class="form-group">
                        <label>结束日期</label>
                        <input type="date" id="category_end_date" name="category_end_date" onchange="loadCategorySummary()">
                    </div>
                    <div class="form-group">
                        <label>项目类型</label>
                        <select id="category_project_name" name="category_project_name" onchange="loadCategorySummary()">
                            <option value="">全部项目</option>
                            <option value="ejj">ejj</option>
                            <option value="dd">dd</option>
                            <option value="fruit">fruit</option>
                        </select>
                    </div>
                </div>
            </div>

            <div id="categoryLoading" class="loading" style="display: none;">正在生成分类统计...</div>
            <div id="categoryError" class="error" style="display: none;"></div>

            <div id="categoryContainer">
                <div class="form-row">
                    <div class="form-group">
                        <div class="summary-card">
                            <h5>总收入</h5>
                            <div class="summary-value" id="categoryTotalIncome">0.00 元</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="summary-card" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                            <h5>总支出</h5>
                            <div class="summary-value" id="categoryTotalExpense">0.00 元</div>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="summary-card" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                            <h5>净收益</h5>
                            <div class="summary-value" id="categoryNetIncome">0.00 元</div>
                        </div>
                    </div>
                </div>

                <h4>收入分类明细</h4>
                <div class="summary-table-container">
                    <table class="summary-table">
                        <thead>
                            <tr>
                                <th>一级分类</th>
                                <th>二级分类</th>
                                <th>金额</th>
                            </tr>
                        </thead>
                        <tbody id="incomeSummaryBody">
                            <tr>
                                <td colspan="3" style="text-align: center;">请选择日期和项目类型查看统计</td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                <h4>支出分类明细</h4>
                <div class="summary-table-container">
                    <table class="summary-table">
                        <thead>
                            <tr>
                                <th>一级分类</th>
                                <th>二级分类</th>
                                <th>金额</th>
                            </tr>
                        </thead>
                        <tbody id="expenseSummaryBody">
                            <tr>
                                <td colspan="3" style="text-align: center;">请选择日期和项目类型查看统计</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                
                <!-- 移动端分类卡片视图 -->
                <div id="categoryCardView" class="summary-card-view">
                    <div style="text-align: center; padding: 20px; color: #666;">
                        请选择日期和项目类型查看统计
                    </div>
                </div>
            </div>
        </div>
    </div>
    </div>

    <script src="../static/js/common.js"></script>
    <script src="../static/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script>
        let categories = [];
        let subcategories = [];
        let accountConfig = {
            balance: {},
            account_name: []
        };

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 设置默认日期为今天
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('settlement_date').value = today;
            document.getElementById('start_date').value = today;
            document.getElementById('end_date').value = today;
            document.getElementById('summary_start_date').value = today;
            document.getElementById('summary_end_date').value = today;
            document.getElementById('category_start_date').value = today;
            document.getElementById('category_end_date').value = today;

        // 加载账户配置数据
        loadAccountConfig();

        // 加载分类数据
        loadCategoryData();

        // 加载项目列表
        loadProjectList();

        // 初始化入账状态显示
        calculateAccountedStatus();

            // 表单提交事件
            document.getElementById('accountForm').addEventListener('submit', function(e) {
                e.preventDefault();
                submitAccountData();
            });

            // 标签切换时重新加载数据
            document.getElementById('records-tab').addEventListener('shown.bs.tab', function() {
                loadRecords();
            });

            document.getElementById('summary-tab').addEventListener('shown.bs.tab', function() {
                loadAccountListForSummary();
                // 自动加载账户统计数据
                setTimeout(loadAccountSummaryForSummaryTab, 100);
            });

            document.getElementById('account-summary-tab').addEventListener('shown.bs.tab', function() {
                // 分类统计标签页不需要加载账户列表
            });
        });

        // 加载账户配置数据
        function loadAccountConfig() {
            fetch('/jk/get_account_config')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        accountConfig = data.data;
                        
                        // 更新工作账户选择列表
                        updateAccountNameSelect();
                        
                        // 更新统计账户选择列表
                        updateSummaryAccountSelect();
                    } else {
                        throw new Error(data.message || '加载账户配置失败');
                    }
                })
                .catch(error => {
                    console.error('加载账户配置失败:', error);
                    showError('加载账户配置失败: ' + error.message);
                });
        }

        // 更新工作账户选择列表
        function updateAccountNameSelect() {
            const select = document.getElementById('account_name');
            select.innerHTML = '<option value="">请选择工作帐户</option>';
            
            accountConfig.account_name.forEach(account => {
                const option = document.createElement('option');
                option.value = account;
                option.textContent = account;
                select.appendChild(option);
            });
        }

        // 更新统计账户选择列表
        function updateSummaryAccountSelect() {
            const select = document.getElementById('summary_account');
            select.innerHTML = '<option value="">全部账户</option>';
            
            accountConfig.account_name.forEach(account => {
                const option = document.createElement('option');
                option.value = account;
                option.textContent = account;
                select.appendChild(option);
            });
        }

        // 加载分类数据
        function loadCategoryData() {
            fetch('/jk/get_categories')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        categories = data.categories;
                        subcategories = data.subcategories;
                    } else {
                        throw new Error(data.message || '加载分类数据失败');
                    }
                })
                .catch(error => {
                    console.error('加载分类数据失败:', error);
                    showError('加载分类数据失败: ' + error.message);
                });
        }

        // 更新分类选项
        function updateCategories() {
            const type = document.getElementById('settlement_type').value;
            const categorySelect = document.getElementById('category_id');
            const subcategorySelect = document.getElementById('subcategory_id');
            
            // 清空选项
            categorySelect.innerHTML = '<option value="">请选择分类</option>';
            subcategorySelect.innerHTML = '<option value="">请选择子分类</option>';

            if (!type) return;

            // 过滤对应类型的分类
            const filteredCategories = categories.filter(cat => cat.category_type === type);
            
            filteredCategories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.category_id;
                option.textContent = category.category_name;
                categorySelect.appendChild(option);
            });
        }

        // 更新子分类选项
        function updateSubcategories() {
            const categoryId = document.getElementById('category_id').value;
            const subcategorySelect = document.getElementById('subcategory_id');
            
            // 清空选项
            subcategorySelect.innerHTML = '<option value="">请选择子分类</option>';

            if (!categoryId) return;

            // 过滤对应分类的子分类
            const filteredSubcategories = subcategories.filter(sub => sub.category_id === categoryId);
            
            filteredSubcategories.forEach(subcategory => {
                const option = document.createElement('option');
                option.value = subcategory.subcategory_id;
                option.textContent = subcategory.subcategory_name;
                subcategorySelect.appendChild(option);
            });
        }

        // 加载项目列表
        function loadProjectList() {
            fetch('/jk/get_projects')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        updateProjectSelects(data.projects);
                    } else {
                        throw new Error(data.message || '加载项目列表失败');
                    }
                })
                .catch(error => {
                    console.error('加载项目列表失败:', error);
                    // 失败时使用默认项目列表
                    const defaultProjects = ['ejj', 'dd', 'fruit'];
                    updateProjectSelects(defaultProjects);
                });
        }

        // 更新项目选择下拉框
        function updateProjectSelects(projects) {
            // 更新记账表单的项目选择
            const projectSelect = document.getElementById('project_name');
            projectSelect.innerHTML = '<option value="ejj" selected>ejj</option>';
            
            projects.forEach(project => {
                if (project !== 'ejj') {
                    const option = document.createElement('option');
                    option.value = project;
                    option.textContent = project;
                    projectSelect.appendChild(option);
                }
            });

            // 更新筛选条件的项目选择
            const filterProjectSelect = document.getElementById('filter_project_name');
            filterProjectSelect.innerHTML = '<option value="">全部项目</option>';
            
            projects.forEach(project => {
                const option = document.createElement('option');
                option.value = project;
                option.textContent = project;
                filterProjectSelect.appendChild(option);
            });

            // 更新分类统计的项目选择
            const categoryProjectSelect = document.getElementById('category_project_name');
            categoryProjectSelect.innerHTML = '<option value="">全部项目</option>';
            
            projects.forEach(project => {
                const option = document.createElement('option');
                option.value = project;
                option.textContent = project;
                categoryProjectSelect.appendChild(option);
            });
        }

        // 计算金额
        function calculateAmount() {
            const quantity = parseFloat(document.getElementById('quantity').value) || 0;
            const unitPrice = parseFloat(document.getElementById('unit_price').value) || 0;
            const amount = quantity * unitPrice;
            
            document.getElementById('amount').value = amount.toFixed(2);
            // 重新计算入账状态
            calculateAccountedStatus();
        }

        // 计算入账状态
        function calculateAccountedStatus() {
            const amount = parseFloat(document.getElementById('amount').value) || 0;
            const settlementAmount = parseFloat(document.getElementById('settlement_amount').value) || 0;
            
            let accountedStatus = 'pending';
            let displayText = '待入账';
            
            if (settlementAmount > 0) {
                if (Math.abs(amount - settlementAmount) < 0.01) { // 考虑浮点数精度
                    accountedStatus = 'completed';
                    displayText = '已入账';
                } else {
                    accountedStatus = 'partial';
                    displayText = '部分入账';
                }
            }
            
            document.getElementById('accounted_status').value = accountedStatus;
            document.getElementById('accounted_status_display').value = displayText;
        }

        // 提交记账数据
        function submitAccountData() {
            const formData = new FormData(document.getElementById('accountForm'));
            const data = Object.fromEntries(formData.entries());
            
            // 验证表单
            if (!validateForm(data)) {
                return;
            }

            const loading = document.getElementById('loading');
            const error = document.getElementById('error');
            const success = document.getElementById('success');
            const submitBtn = document.querySelector('.submit-btn');
            
            loading.style.display = 'block';
            error.style.display = 'none';
            success.style.display = 'none';
            submitBtn.disabled = true;
            submitBtn.textContent = '保存中...';

            fetch('/jk/save_settlement', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                loading.style.display = 'none';
                if (result.success) {
                    showSuccess('记账信息保存成功！');
                    document.getElementById('accountForm').reset();
                    // 重置日期为今天
                    const today = new Date().toISOString().split('T')[0];
                    document.getElementById('settlement_date').value = today;
                    // 重新计算金额
                    calculateAmount();
                } else {
                    throw new Error(result.message || '保存失败');
                }
            })
            .catch(error => {
                loading.style.display = 'none';
                showError('保存失败: ' + error.message);
            })
            .finally(() => {
                submitBtn.disabled = false;
                submitBtn.textContent = '保存记账信息';
            });
        }

        // 表单验证
        function validateForm(data) {
            const error = document.getElementById('error');
            error.style.display = 'none';

            const requiredFields = [
                'settlement_date', 'settlement_type', 'category_id', 'subcategory_id',
                'item_name', 'quantity', 'unit_price', 'settler_name'
            ];
            
            for (const field of requiredFields) {
                if (!data[field] || data[field].toString().trim() === '') {
                    showError(`${getFieldName(field)}不能为空`);
                    return false;
                }
            }

            // 检查数字字段
            const numberFields = ['quantity', 'unit_price'];
            for (const field of numberFields) {
                const value = parseFloat(data[field]);
                if (isNaN(value) || value < 0) {
                    showError(`${getFieldName(field)}必须为有效的非负数`);
                    return false;
                }
            }

            return true;
        }

        // 获取字段中文名称
        function getFieldName(field) {
            const fieldNames = {
                'settlement_date': '结算日期',
                'settlement_type': '收支类型',
                'category_id': '一级分类',
                'subcategory_id': '二级分类',
                'item_name': '结算内容',
                'quantity': '数量',
                'unit_price': '单价',
                'settler_name': '结算收款人'
            };
            return fieldNames[field] || field;
        }

        // 显示错误信息
        function showError(message) {
            const error = document.getElementById('error');
            error.style.display = 'block';
            error.textContent = message;
            
            setTimeout(() => {
                error.style.display = 'none';
            }, 3000);
        }

        // 显示成功信息
        function showSuccess(message) {
            const success = document.getElementById('success');
            success.style.display = 'block';
            success.textContent = message;
            
            setTimeout(() => {
                success.style.display = 'none';
            }, 3000);
        }

        // 加载记录数据
        function loadRecords() {
            const loading = document.getElementById('recordsLoading');
            const error = document.getElementById('recordsError');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            const params = new URLSearchParams({
                start_date: document.getElementById('start_date').value,
                end_date: document.getElementById('end_date').value,
                type: document.getElementById('filter_type').value,
                accounted_status: document.getElementById('filter_accounted_status').value,
                project_name: document.getElementById('filter_project_name').value
            });

            fetch(`/jk/get_settlements?${params}`)
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success) {
                        console.log('结算数据：',data);
                        renderRecordsTable(data.records);
                    } else {
                        throw new Error(data.message || '加载记录失败');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载记录失败: ' + error.message;
                });
        }

            // 渲染记录表格
        function renderRecordsTable(records) {
            const tbody = document.getElementById('recordsTableBody');
            tbody.innerHTML = '';

            if (records.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="10" style="text-align: center;">没有找到相关记录</td></tr>';
                return;
            }

            // 检查屏幕宽度，决定使用表格还是卡片布局
            const isMobile = window.innerWidth <= 768;
            
            if (isMobile) {
                    // 移动端使用卡片布局
                    records.forEach(record => {
                        const card = document.createElement('div');
                        card.className = `record-card ${record.settlement_type === 'income' ? 'income-card' : 'expense-card'}`;
                        
                        // 计算未结算金额
                        const unsettledAmount = parseFloat(record.amount) - (parseFloat(record.settled_amount) || 0);
                        // 判断是否禁用编辑按钮（未结算金额为0时禁用）
                        const isEditDisabled = Math.abs(unsettledAmount) < 0.01; // 考虑浮点数精度
                        
                        card.innerHTML = `
                            <div class="record-card-header">
                                <strong>${formatDate(record.settlement_date)}</strong>
                                <span class="record-type">${record.settlement_type === 'income' ? '收入' : '支出'}</span>
                            </div>
                            <div class="record-card-body">
                                <div><strong>结算内容:</strong> ${record.item_name}</div>
                                <div><strong>结算对象:</strong> ${record.settled_with || '-'}</div>
                                <div><strong>项目类型:</strong> ${record.project_name || 'ejj'}</div>
                                <div><strong>分类:</strong> ${getCategoryName(record.category_id)} - ${getSubcategoryName(record.subcategory_id)}</div>
                                <div><strong>金额:</strong> ${parseFloat(record.amount).toFixed(2)}</div>
                                <div><strong>未结算金额:</strong> ${unsettledAmount.toFixed(2)}</div>
                                <div>
                                    <span class="${getAccountedStatusClass(record.accounted_status)}">
                                        入账状态: ${getAccountedStatusText(record.accounted_status)}
                                    </span>
                                </div>
                            </div>
                            <div class="record-card-actions">
                                <button class="btn btn-sm btn-outline-primary" onclick="editRecord('${record.settlement_id}')" ${isEditDisabled ? 'disabled' : ''}> 结算</button>
                                <button class="btn btn-sm btn-outline-danger" onclick="deleteRecord('${record.settlement_id}')">删除</button>
                            </div>
                        `;
                        tbody.appendChild(card);
                    });
            } else {
                // PC端使用表格布局
            records.forEach(record => {
                const row = document.createElement('tr');
                row.className = record.settlement_type === 'income' ? 'income-row' : 'expense-row';
                
                // 计算未结算金额
                const unsettledAmount = parseFloat(record.amount) - (parseFloat(record.settled_amount) || 0);
                // 判断是否禁用编辑按钮（未结算金额为0时禁用）
                const isEditDisabled = Math.abs(unsettledAmount) < 0.01; // 考虑浮点数精度
                
                row.innerHTML = `
                    <td>${formatDate(record.settlement_date)}</td>
                    <td>${record.settlement_type === 'income' ? '收入' : '支出'}</td>
                    <td>${record.settled_with || '-'}</td>
                    <td>${record.item_name}</td>
                    <td>${record.project_name || 'ejj'}</td>
                    <td>${getCategoryName(record.category_id)} - ${getSubcategoryName(record.subcategory_id)}</td>
                    <td style="text-align: right;">${parseFloat(record.amount).toFixed(2)}</td>
                    <td style="text-align: right;">${unsettledAmount.toFixed(2)}</td>
                    <td class="${getAccountedStatusClass(record.accounted_status)}">
                        ${getAccountedStatusText(record.accounted_status)}
                    </td>
                    <td>
                        <button class="btn btn-sm btn-outline-primary" onclick="editRecord('${record.settlement_id}')" ${isEditDisabled ? 'disabled' : ''}>编辑</button>
                        <button class="btn btn-sm btn-outline-danger" onclick="deleteRecord('${record.settlement_id}')">删除</button>
                    </td>
                `;
                tbody.appendChild(row);
            });
            }
        }

        // 获取分类名称
        function getCategoryName(categoryId) {
            const category = categories.find(cat => cat.category_id === categoryId);
            return category ? category.category_name : '未知分类';
        }

        // 获取子分类名称
        function getSubcategoryName(subcategoryId) {
            const subcategory = subcategories.find(sub => sub.subcategory_id === subcategoryId);
            return subcategory ? subcategory.subcategory_name : '未知子分类';
        }

        // 获取入账状态对应的CSS类
        function getAccountedStatusClass(accountedStatus) {
            switch(accountedStatus) {
                case 'completed':
                    return 'accounted-true';
                case 'pending':
                    return 'accounted-false';
                case 'partial':
                    return 'accounted-partial';
                default:
                    return 'accounted-false';
            }
        }

        // 获取入账状态对应的文本
        function getAccountedStatusText(accountedStatus) {
            switch(accountedStatus) {
                case 'completed':
                    return '已入账';
                case 'pending':
                    return '待入账';
                case 'partial':
                    return '部分入账';
                default:
                    return '待入账';
            }
        }

        // 格式化日期为yyyy-mm-dd格式
        function formatDate(dateString) {
            if (!dateString) return '';
            
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return dateString;
            
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            
            return `${year}-${month}-${day}`;
        }

        // 查询本月数据
        function queryThisMonth() {
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), today.getMonth(), 1);
            const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0);
            
            document.getElementById('start_date').value = formatDate(firstDay);
            document.getElementById('end_date').value = formatDate(lastDay);
            
            // 自动触发搜索
            loadRecords();
        }

        // 查询本年数据
        function queryThisYear() {
            const today = new Date();
            const firstDay = new Date(today.getFullYear(), 0, 1);
            const lastDay = new Date(today.getFullYear(), 11, 31);
            
            document.getElementById('start_date').value = formatDate(firstDay);
            document.getElementById('end_date').value = formatDate(lastDay);
            
            // 自动触发搜索
            loadRecords();
        }

        // 加载统计分类选项
        function loadSummaryCategories() {
            const select = document.getElementById('summary_category');
            select.innerHTML = '<option value="">全部分类</option>';
            
            categories.forEach(category => {
                const option = document.createElement('option');
                option.value = category.category_id;
                option.textContent = category.category_name;
                select.appendChild(option);
            });
        }

        // 加载统计汇总
        function loadSummary() {
            const loading = document.getElementById('summaryLoading');
            const error = document.getElementById('summaryError');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            const params = new URLSearchParams({
                start_date: document.getElementById('summary_start_date').value,
                end_date: document.getElementById('summary_end_date').value,
                category_id: document.getElementById('summary_category').value
            });

            fetch(`/jk/get_summary?${params}`)
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success) {
                        renderSummary(data.summary);
                    } else {
                        throw new Error(data.message || '加载统计失败');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载统计失败: ' + error.message;
                });
        }

        // 渲染统计汇总
        function renderSummary(summary) {
            document.getElementById('totalIncome').textContent = `${summary.total_income.toFixed(2)} 元`;
            document.getElementById('totalExpense').textContent = `${summary.total_expense.toFixed(2)} 元`;
            document.getElementById('netIncome').textContent = `${summary.net_income.toFixed(2)} 元`;

            const tbody = document.getElementById('categorySummaryBody');
            const cardView = document.getElementById('summaryCardView');
            
            tbody.innerHTML = '';
            cardView.innerHTML = '';

            if (summary.category_details.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4" style="text-align: center;">没有相关数据</td></tr>';
                cardView.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">没有相关数据</div>';
                return;
            }

            // 检查屏幕宽度，决定使用表格还是卡片布局
            const isMobile = window.innerWidth <= 768;
            
            if (isMobile) {
                // 移动端使用卡片布局
                summary.category_details.forEach(detail => {
                    const card = document.createElement('div');
                    card.className = 'summary-card-item';
                    
                    card.innerHTML = `
                        <div class="summary-card-header">${detail.category_name}</div>
                        <div class="summary-card-detail">
                            <span>收入:</span>
                            <span class="summary-income">${detail.income.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail">
                            <span>支出:</span>
                            <span class="summary-expense">${detail.expense.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail summary-net">
                            <span>净额:</span>
                            <span>${(detail.income - detail.expense).toFixed(2)} 元</span>
                        </div>
                    `;
                    cardView.appendChild(card);
                });
            } else {
                // PC端使用表格布局
                summary.category_details.forEach(detail => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${detail.category_name}</td>
                        <td>${detail.income.toFixed(2)} 元</td>
                        <td>${detail.expense.toFixed(2)} 元</td>
                        <td>${(detail.income - detail.expense).toFixed(2)} 元</td>
                    `;
                    tbody.appendChild(row);
                });
            }
        }

        // 编辑记录
        function editRecord(settlementId) {
            // 首先获取记录详情
            fetch(`/jk/get_settlements?settlement_id=${settlementId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.records.length > 0) {
                        // 手动查找匹配的记录（因为API可能没有正确过滤）
                        const record = data.records.find(r => r.settlement_id === settlementId);
                        if (record) {
                            openEditModal(record);
                        } else {
                            showError('未找到对应的记录');
                        }
                    } else {
                        throw new Error('获取记录详情失败');
                    }
                })
                .catch(error => {
                    showError('获取记录详情失败: ' + error.message);
                });
        }

        // 打开编辑模态框
        function openEditModal(record) {
            // 创建或显示编辑模态框
            let modal = document.getElementById('editModal');
            if (!modal) {
                createEditModal();
                modal = document.getElementById('editModal');
            }
            
            // 填充表单数据
            document.getElementById('edit_settlement_id').value = record.settlement_id;
            
            // 设置结算日期为今天（默认值）
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('edit_settlement_date').value = today;
            
            // 使用从服务器获取的该行的实际未结算金额数据（确保转换为数字）
            const amount = parseFloat(record.amount) || 0;
            const settledAmount = parseFloat(record.settled_amount) || 0;
            const unsettledAmount = amount - settledAmount;
            document.getElementById('edit_settled_amount').value = unsettledAmount.toFixed(2);
            
            // 显示当前金额信息（基于该行的实际数据）
            document.getElementById('edit_current_amount').textContent = `总金额: ${amount.toFixed(2)} 元`;
            document.getElementById('edit_current_settled').textContent = `已结算: ${settledAmount.toFixed(2)} 元`;
            
            // 显示模态框
            const bootstrapModal = new bootstrap.Modal(modal);
            bootstrapModal.show();
        }

        // 创建编辑模态框
        function createEditModal() {
            const modalHTML = `
                <div class="modal fade" id="editModal" tabindex="-1" aria-labelledby="editModalLabel" aria-hidden="true">
                    <div class="modal-dialog">
                        <div class="modal-content">
                            <div class="modal-header">
                                <h5 class="modal-title" id="editModalLabel">编辑结算记录</h5>
                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <div id="editError" class="error" style="display: none;"></div>
                                <div id="editSuccess" class="success" style="display: none;"></div>
                                
                                <input type="hidden" id="edit_settlement_id">
                                
                                <div class="form-group">
                                    <label class="required">结算日期</label>
                                    <input type="date" id="edit_settlement_date" class="form-control" required>
                                </div>
                                
                                <div class="form-group">
                                    <label class="required">结算金额 (元)</label>
                                    <input type="number" step="0.01" id="edit_settled_amount" class="form-control" min="0" required>
                                </div>
                                
                                <div class="form-group">
                                    <div id="edit_current_amount" style="color: #666; font-size: 14px;"></div>
                                    <div id="edit_current_settled" style="color: #666; font-size: 14px;"></div>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                                <button type="button" class="btn btn-primary" onclick="updateSettlement()">保存</button>
                            </div>
                        </div>
                    </div>
                </div>
            `;
            
            document.body.insertAdjacentHTML('beforeend', modalHTML);
        }

        // 更新结算记录
        function updateSettlement() {
            const settlementId = document.getElementById('edit_settlement_id').value;
            const settlementDate = document.getElementById('edit_settlement_date').value;
            const settledAmount = parseFloat(document.getElementById('edit_settled_amount').value);
            
            if (!settlementDate) {
                showEditError('结算日期不能为空');
                return;
            }
            
            if (isNaN(settledAmount) || settledAmount < 0) {
                showEditError('结算金额必须为有效的非负数');
                return;
            }

            const data = {
                settlement_id: settlementId,
                settlement_date: settlementDate,
                settled_amount: settledAmount
            };

            fetch('/jk/update_settlement', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    showEditSuccess('结算记录更新成功！');
                    // 关闭模态框并重新加载记录
                    setTimeout(() => {
                        const modal = bootstrap.Modal.getInstance(document.getElementById('editModal'));
                        modal.hide();
                        loadRecords();
                    }, 1500);
                } else {
                    throw new Error(result.message || '更新失败');
                }
            })
            .catch(error => {
                showEditError('更新失败: ' + error.message);
            });
        }

        // 显示编辑错误信息
        function showEditError(message) {
            const error = document.getElementById('editError');
            error.style.display = 'block';
            error.textContent = message;
        }

        // 显示编辑成功信息
        function showEditSuccess(message) {
            const success = document.getElementById('editSuccess');
            success.style.display = 'block';
            success.textContent = message;
        }

        // 删除记录
        function deleteRecord(settlementId) {
            if (confirm('确定要删除这条记录吗？本操作不可恢复！！')) {
                fetch('/jk/delete_settlement', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ settlement_id: settlementId })
                })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        showSuccess('记录删除成功！');
                        // 重新加载记录列表
                        loadRecords();
                    } else {
                        throw new Error(result.message || '删除失败');
                    }
                })
                .catch(error => {
                    showError('删除失败: ' + error.message);
                });
            }
        }

        // 加载账户列表（用于分类统计标签页）
        function loadAccountList() {
            fetch('/jk/get_accounts')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('account_filter');
                        select.innerHTML = '<option value="">全部账户</option>';
                        
                        data.accounts.forEach(account => {
                            const option = document.createElement('option');
                            option.value = account;
                            option.textContent = account;
                            select.appendChild(option);
                        });
                    } else {
                        throw new Error(data.message || '加载账户列表失败');
                    }
                })
                .catch(error => {
                    console.error('加载账户列表失败:', error);
                });
        }

        // 加载账户列表（用于入账账户统计标签页）
        function loadAccountListForSummary() {
            fetch('/jk/get_accounts')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const select = document.getElementById('summary_account');
                        select.innerHTML = '<option value="">全部账户</option>';
                        
                        data.accounts.forEach(account => {
                            const option = document.createElement('option');
                            option.value = account;
                            option.textContent = account;
                            select.appendChild(option);
                        });
                    } else {
                        throw new Error(data.message || '加载账户列表失败');
                    }
                })
                .catch(error => {
                    console.error('加载账户列表失败:', error);
                });
        }

        // 加载账户统计
        function loadAccountSummary() {
            const loading = document.getElementById('accountLoading');
            const error = document.getElementById('accountError');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            const params = new URLSearchParams({
                start_date: document.getElementById('account_start_date').value,
                end_date: document.getElementById('account_end_date').value,
                account_name: document.getElementById('account_filter').value
            });

            fetch(`/jk/get_account_summary?${params}`)
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success) {
                        renderAccountSummary(data.summary);
                    } else {
                        throw new Error(data.message || '加载账户统计失败');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载账户统计失败: ' + error.message;
                });
        }

        // 加载入账账户统计（用于入账账户统计标签页）
        function loadAccountSummaryForSummaryTab() {
            const loading = document.getElementById('summaryLoading');
            const error = document.getElementById('summaryError');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            const params = new URLSearchParams({
                start_date: document.getElementById('summary_start_date').value,
                end_date: document.getElementById('summary_end_date').value,
                account_name: document.getElementById('summary_account').value
            });

            fetch(`/jk/get_account_summary?${params}`)
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success) {
                        // console.log('入账账户数据：',data.summary);
                        renderAccountSummaryForSummaryTab(data.summary);
                    } else {
                        throw new Error(data.message || '加载账户统计失败');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    error.style.display = 'block';
                    error.textContent = '加载账户统计失败: ' + error.message;
                });
        }

        // 渲染入账账户统计汇总（用于入账账户统计标签页）
        function renderAccountSummaryForSummaryTab(summary) {
            // 计算净收益（总收入 - 总支出）
            const netIncome = summary.total_income - summary.total_expense;
            
            // 获取选中的账户名称
            const selectedAccount = document.getElementById('summary_account').value;
            
            // 如果有选中特定账户，加上该账户的初始余额
            let finalNetIncome = netIncome;
            if (selectedAccount && accountConfig.balance[selectedAccount] !== undefined) {
                finalNetIncome += accountConfig.balance[selectedAccount];
            }
            
            document.getElementById('totalIncome').textContent = `${summary.total_income.toFixed(2)} 元`;
            document.getElementById('totalExpense').textContent = `${summary.total_expense.toFixed(2)} 元`;
            document.getElementById('netIncome').textContent = `${finalNetIncome.toFixed(2)} 元`;

            const cardView = document.getElementById('summaryCardView');
            cardView.innerHTML = '';

            if (summary.account_details.length === 0) {
                cardView.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">没有相关数据</div>';
                return;
            }

            // 检查屏幕宽度，决定使用表格还是卡片布局
            const isMobile = window.innerWidth <= 768;
            
            if (isMobile) {
                // 移动端使用卡片布局
                summary.account_details.forEach(account => {
                    const card = document.createElement('div');
                    card.className = 'summary-card-item';
                    
                    // 计算该账户的最终余额（加上初始余额）
                    const initialBalance = accountConfig.balance[account.account_name] || 0;
                    const finalBalance = account.balance + initialBalance;
                    
                    card.innerHTML = `
                        <div class="summary-card-header">${account.account_name}</div>
                        <div class="summary-card-detail">
                            <span>收入:</span>
                            <span class="summary-income">${account.income.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail">
                            <span>支出:</span>
                            <span class="summary-expense">${account.expense.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail">
                            <span>初始余额:</span>
                            <span>${initialBalance.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail summary-net">
                            <span>最终余额:</span>
                            <span>${finalBalance.toFixed(2)} 元</span>
                        </div>
                    `;
                    cardView.appendChild(card);
                });
            } else {
                // PC端使用表格布局
                summary.account_details.forEach(account => {
                    const card = document.createElement('div');
                    card.className = 'summary-card-item';
                    
                    // 计算该账户的最终余额（加上初始余额）
                    const initialBalance = accountConfig.balance[account.account_name] || 0;
                    const finalBalance = account.balance + initialBalance;
                    
                    card.innerHTML = `
                        <div class="summary-card-header">${account.account_name}</div>
                        <div class="summary-card-detail">
                            <span>收入:</span>
                            <span class="summary-income">${account.income.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail">
                            <span>支出:</span>
                            <span class="summary-expense">${account.expense.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail">
                            <span>初始余额:</span>
                            <span>${initialBalance.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail summary-net">
                            <span>最终余额:</span>
                            <span>${finalBalance.toFixed(2)} 元</span>
                        </div>
                    `;
                    cardView.appendChild(card);
                });
            }
        }

        // 加载分类统计
        function loadCategorySummary() {
            const loading = document.getElementById('categoryLoading');
            const error = document.getElementById('categoryError');
            
            loading.style.display = 'block';
            error.style.display = 'none';

            const startDate = document.getElementById('category_start_date').value;
            const endDate = document.getElementById('category_end_date').value;
            const projectName = document.getElementById('category_project_name').value;

            const params = new URLSearchParams({
                start_date: startDate,
                end_date: endDate,
                project_name: projectName
            });

            fetch(`/jk/get_category_summary?${params}`)
                .then(response => response.json())
                .then(data => {
                    loading.style.display = 'none';
                    if (data.success) {
                        renderCategorySummary(data.summary);
                    } else {
                        throw new Error(data.message || '加载分类统计失败');
                    }
                })
                .catch(error => {
                    loading.style.display = 'none';
                    const errorElement = document.getElementById('categoryError');
                    errorElement.style.display = 'block';
                    errorElement.textContent = '加载分类统计失败: ' + error.message;
                });
        }
        

        // 渲染分类统计汇总
        function renderCategorySummary(summary) {
            // 手动计算净收益（总收入 - 总支出）
            const netIncome = summary.total_income - summary.total_expense;
            
            document.getElementById('categoryTotalIncome').textContent = `${summary.total_income.toFixed(2)} 元`;
            document.getElementById('categoryTotalExpense').textContent = `${summary.total_expense.toFixed(2)} 元`;
            document.getElementById('categoryNetIncome').textContent = `${netIncome.toFixed(2)} 元`;

            const incomeTbody = document.getElementById('incomeSummaryBody');
            const expenseTbody = document.getElementById('expenseSummaryBody');
            const cardView = document.getElementById('categoryCardView');
            
            incomeTbody.innerHTML = '';
            expenseTbody.innerHTML = '';
            cardView.innerHTML = '';

            if (summary.category_details.length === 0) {
                incomeTbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">没有相关数据</td></tr>';
                expenseTbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">没有相关数据</td></tr>';
                cardView.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">没有相关数据</div>';
                return;
            }

            // 按一级分类分组
            const groupedByCategory = {};
            summary.category_details.forEach(detail => {
                if (!groupedByCategory[detail.category_name]) {
                    groupedByCategory[detail.category_name] = [];
                }
                groupedByCategory[detail.category_name].push(detail);
            });

            // 渲染收入表格
            Object.keys(groupedByCategory).forEach(categoryName => {
                const categoryDetails = groupedByCategory[categoryName];
                let hasIncome = false;
                
                // 检查该分类是否有收入数据
                categoryDetails.forEach(detail => {
                    if (detail.income > 0) {
                        hasIncome = true;
                    }
                });

                if (hasIncome) {
                    // 添加一级分类行
                    const categoryRow = document.createElement('tr');
                    categoryRow.className = 'category-header-row';
                    categoryRow.innerHTML = `
                        <td><strong>${categoryName}</strong></td>
                        <td></td>
                        <td><strong>${categoryDetails.reduce((sum, detail) => sum + detail.income, 0).toFixed(2)} 元</strong></td>
                    `;
                    incomeTbody.appendChild(categoryRow);

                    // 添加二级分类行
                    categoryDetails.forEach(detail => {
                        if (detail.income > 0) {
                            const subcategoryRow = document.createElement('tr');
                            subcategoryRow.className = 'subcategory-row';
                            subcategoryRow.innerHTML = `
                                <td></td>
                                <td>${detail.subcategory_name}</td>
                                <td>${detail.income.toFixed(2)} 元</td>
                            `;
                            incomeTbody.appendChild(subcategoryRow);
                        }
                    });
                }
            });

            // 渲染支出表格
            Object.keys(groupedByCategory).forEach(categoryName => {
                const categoryDetails = groupedByCategory[categoryName];
                let hasExpense = false;
                
                // 检查该分类是否有支出数据
                categoryDetails.forEach(detail => {
                    if (detail.expense > 0) {
                        hasExpense = true;
                    }
                });

                if (hasExpense) {
                    // 添加一级分类行
                    const categoryRow = document.createElement('tr');
                    categoryRow.className = 'category-header-row';
                    categoryRow.innerHTML = `
                        <td><strong>${categoryName}</strong></td>
                        <td></td>
                        <td><strong>${categoryDetails.reduce((sum, detail) => sum + detail.expense, 0).toFixed(2)} 元</strong></td>
                    `;
                    expenseTbody.appendChild(categoryRow);

                    // 添加二级分类行
                    categoryDetails.forEach(detail => {
                        if (detail.expense > 0) {
                            const subcategoryRow = document.createElement('tr');
                            subcategoryRow.className = 'subcategory-row';
                            subcategoryRow.innerHTML = `
                                <td></td>
                                <td>${detail.subcategory_name}</td>
                                <td>${detail.expense.toFixed(2)} 元</td>
                            `;
                            expenseTbody.appendChild(subcategoryRow);
                        }
                    });
                }
            });

            // 如果没有数据，显示提示
            if (incomeTbody.children.length === 0) {
                incomeTbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">没有收入数据</td></tr>';
            }
            if (expenseTbody.children.length === 0) {
                expenseTbody.innerHTML = '<tr><td colspan="3" style="text-align: center;">没有支出数据</td></tr>';
            }

            // 移动端卡片视图 - 按分类分组显示
            const isMobile = window.innerWidth <= 768;
            if (isMobile) {
                // 按一级分类分组
                Object.keys(groupedByCategory).forEach(categoryName => {
                    const categoryDetails = groupedByCategory[categoryName];
                    
                    // 添加一级分类标题
                    const categoryHeader = document.createElement('div');
                    categoryHeader.className = 'category-header-mobile';
                    categoryHeader.innerHTML = `<h5>${categoryName}</h5>`;
                    cardView.appendChild(categoryHeader);

                    // 添加收入卡片
                    let hasIncome = false;
                    categoryDetails.forEach(detail => {
                        if (detail.income > 0) {
                            hasIncome = true;
                            const card = document.createElement('div');
                            card.className = 'summary-card-item income-card-mobile';
                            
                            card.innerHTML = `
                                <div class="summary-card-header">${detail.subcategory_name}</div>
                                <div class="summary-card-detail">
                                    <span>收入:</span>
                                    <span class="summary-income">${detail.income.toFixed(2)} 元</span>
                                </div>
                            `;
                            cardView.appendChild(card);
                        }
                    });

                    // 添加支出卡片
                    let hasExpense = false;
                    categoryDetails.forEach(detail => {
                        if (detail.expense > 0) {
                            hasExpense = true;
                            const card = document.createElement('div');
                            card.className = 'summary-card-item expense-card-mobile';
                            
                            card.innerHTML = `
                                <div class="summary-card-header">${detail.subcategory_name}</div>
                                <div class="summary-card-detail">
                                    <span>支出:</span>
                                    <span class="summary-expense">${detail.expense.toFixed(2)} 元</span>
                                </div>
                            `;
                            cardView.appendChild(card);
                        }
                    });

                    // 如果没有数据，添加提示
                    if (!hasIncome && !hasExpense) {
                        const emptyCard = document.createElement('div');
                        emptyCard.className = 'summary-card-item';
                        emptyCard.innerHTML = `<div style="text-align: center; color: #666;">暂无数据</div>`;
                        cardView.appendChild(emptyCard);
                    }
                });
            }
        }

        // 渲染账户统计汇总（用于分类统计标签页）
        function renderAccountSummary(summary) {
            document.getElementById('accountTotalIncome').textContent = `${summary.total_income.toFixed(2)} 元`;
            document.getElementById('accountTotalExpense').textContent = `${summary.total_expense.toFixed(2)} 元`;
            document.getElementById('accountTotalBalance').textContent = `${summary.total_balance.toFixed(2)} 元`;

            const tbody = document.getElementById('accountSummaryBody');
            const cardView = document.getElementById('accountCardView');
            
            tbody.innerHTML = '';
            cardView.innerHTML = '';

            if (summary.account_details.length === 0) {
                tbody.innerHTML = '<tr><td colspan="4, style="text-align: center;">没有相关数据</td></tr>';
                cardView.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">没有相关数据</div>';
                return;
            }

            // 检查屏幕宽度，决定使用表格还是卡片布局
            const isMobile = window.innerWidth <= 768;
            
            if (isMobile) {
                // 移动端使用卡片布局
                summary.account_details.forEach(account => {
                    const card = document.createElement('div');
                    card.className = 'summary-card-item';
                    
                    card.innerHTML = `
                        <div class="summary-card-header">${account.account_name}</div>
                        <div class="summary-card-detail">
                            <span>收入:</span>
                            <span class="summary-income">${account.income.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail">
                            <span>支出:</span>
                            <span class="summary-expense">${account.expense.toFixed(2)} 元</span>
                        </div>
                        <div class="summary-card-detail summary-net">
                            <span>余额:</span>
                            <span>${account.balance.toFixed(2)} 元</span>
                        </div>
                    `;
                    cardView.appendChild(card);
                });
            } else {
                // PC端使用表格布局
                summary.account_details.forEach(account => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${account.account_name}</td>
                        <td>${account.income.toFixed(2)} 元</td>
                        <td>${account.expense.toFixed(2)} 元</td>
                        <td>${account.balance.toFixed(2)} 元</td>
                    `;
                    tbody.appendChild(row);
                });
            }
        }
    </script>
</body>
</html>
